package com.paso.nacosdiscoveryspringcloudgateway.config;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.paso.mycommons.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;


@Configuration
@Slf4j
public class FilterConfig implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        // 获取请求的URI
        String uri = exchange.getRequest().getURI().getPath();
        log.info("====================uri: " + uri);


        ArrayList<String> skipAuthUrls = new ArrayList<>();

        // 添加不需要验证的URI到动态数组
        skipAuthUrls.add("/login/user/login");
        skipAuthUrls.add("/login/user/info");
        skipAuthUrls.add("/login/user/logout");

        //跳过不需要验证的路径
        if (skipAuthUrls.contains(uri)) {
            return chain.filter(exchange);
        }



        // 获取请求头信息
        ServerHttpRequest request = exchange.getRequest();
        HttpHeaders headers = request.getHeaders();
        String token = headers.getFirst("X-Token");


        ServerHttpResponse response = exchange.getResponse();


        if (StringUtils.isBlank(token)) {
            log.error("token not found");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }


        // 验证 token
        if (!JwtUtil.checkSign(token)){
            log.error("invalid token");
            response.setStatusCode(HttpStatus.FORBIDDEN);
            return response.setComplete();
        }


        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
